#include "TcpSocket.h"
#include"TcpServer.h"
#include"SecKeyShm.h"
#include"ShareMemory.h"
#include<iostream>
#include"xsec.h"
using namespace std;
struct SockInfo
{
    TcpServer* s;
    TcpSocket* tcp;
    struct sockaddr_in addr;
};

void* working(void* arg)
{
    struct SockInfo* pinfo = static_cast<struct SockInfo*>(arg);
  
    // 5. 通信
    while (1)
    {
        printf("接收数据: .....\n");
        int clientid=0;
        int serverid=0;
        string msg = pinfo->tcp->recvMsg(clientid,serverid);
        if (!msg.empty())
        {
            cout << msg << endl << endl << endl;
            //将密文写入文件
            ofstream ofs("cipher2.txt",ios::binary);
            if(!ofs)
            {
            	ofs.close();
            	break;
            }
            ofs.write(msg.c_str(),msg.size());
            ofs.close();
            //从共享内存中拿出密钥开始解密
            SecKeyShm *shm=new SecKeyShm(0x1234);
  					NodeSHMInfo node;
  					memset(&node,0x00,sizeof(NodeSHMInfo));
  					char cidtmp[10];
  					char sidtmp[10];
  					sprintf(cidtmp,"%d",clientid);
  					sprintf(sidtmp,"%d",serverid);
  					shm->shmRead(cidtmp,sidtmp,&node);
  					XSec sec;
  					string passwd=string(node.seckey,strlen(node.seckey));
            sec.XSecEncryptFile(X3DES_CBC, passwd, "cipher2.txt", "plaint2.txt", false);
            sec.Close();
        }
        else
        {
            break;
        }
    }
    delete pinfo->tcp;
    delete pinfo;
    return nullptr;
}
int main()
{
    // 1. 创建监听的套接字
    TcpServer s;
    // 2. 绑定本地的IP port并设置监听
    s.setListen(10000);
    // 3. 阻塞并等待客户端的连接
    while (1)
    {
        
        SockInfo* info = new SockInfo;
        TcpSocket* tcp = s.acceptConn(&info->addr);
        if (tcp == nullptr)
        {
            cout << "重试...." << endl;
            continue;
        }
        // 创建子线程
        pthread_t tid;
        info->s = &s;
        info->tcp = tcp;

        pthread_create(&tid, NULL, working, info);
        pthread_detach(tid);
        
    }

    return 0;
}